// @flow
import React, { Component } from 'react'
import styles from './Spectrum.css'
// import testJson from './test.json'
import { message, Spin, Row, Col, Popover, Radio, Button } from 'antd'
import Highcharts from 'highcharts-release'
import R from 'ramda'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import moment from 'moment'
const RadioGroup = Radio.Group

import type { Location } from 'react-router'
const { search } = location
const paramsString = search.substring(1)
const searchParams = new URLSearchParams(paramsString)
const requestType = searchParams.get('requestType')

type Props = {
  location: Location,
  visible: boolean,
  closeModal: Function,
  checkTime: number,
  channel_id: number,
  checkName: string,
  deviceData: Object,
  historyCond: Object
}

type States = {
  chartData: Array<any>,
  chartData2: Array<any>,
  xData: Array<any>,
  visible: boolean,
  loading: boolean,
  loading2: boolean,
  requestData: Object,
  Indictor: Array<Object>,
  infoData: Array<Object>,
  samples: string, // 采样点
  samplesFinal: string, // 展示用到的采样点数
  activity: string, // 速度计算方式（有键无健）
  activityFinal: string, // 展示用到的速度计算方式
  checkName: string, // 通道名字
  checkNameFinal: string, // 展示用到的通道名字
  plainOptions: Array<Object>,
  channelValue: string,
  channelData: Array<Object>
}
class Spectrum extends Component {
  props: Props
  state: States
  getDynamicData: Function
  closeModal: Function
  getRequestData: Function
  getIndictor: Function
  getChannel: Function
  constructor (props: Object) {
    super(props)
    this.state = {
      xData: [],
      visible: true,
      chartData: [],
      chartData2: [],
      loading: false,
      loading2: false,
      requestData: {},
      Indictor: [],
      infoData: [],
      samples: '', // 采样点
      samplesFinal: '', // 展示用到的采样点数
      activity: '', // 速度计算方式（有键无健）
      activityFinal: '', // 展示用到的速度计算方式
      // checkName: this.props.checkName, // 通道名字
      checkName: '',
      checkNameFinal: '', // 展示用到的通道名字
      plainOptions: [],
      channelValue: this.props.channel_id,
      channelData: []
    }
    this.getDynamicData = this.getDynamicData.bind(this)
    this.closeModal = this.closeModal.bind(this)
    this.getRequestData = this.getRequestData.bind(this)
    this.getIndictor = this.getIndictor.bind(this)
    this.getChannel = this.getChannel.bind(this)
  }
  componentWillMount () {
    console.log(this.props)
    this.getIndictor() // 取所有的指标(里面会执行getChannel())
  }

  componentWillReceiveProps (nextProps: Props) {
    if (!R.equals(nextProps, this.props)) {
      this.getChannel(nextProps) // 找到对应channel_id对应的samples值(里面有请求time函数)
    }
  }
  getChannel (props) {
    // 通道
    const component = this
    const { deviceData, historyCond, channel_id } = props
    const sensorType = historyCond.monitors[0].sensorType
    const id = deviceData.id
    let api = `${__SERVICE_API__}`
    if (requestType === 'wx') {
      api = `${__WXSERVICE_API__}`
    }
    universalFetch(`${api}device/devices/${id}/channel-ids`)
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        const channelData = json.result.filter((dd) => dd.sensorType === sensorType)
        if (channelData.length > 0) {
          this.setState({
            channelData: channelData,
            plainOptions: channelData[0].channelIds.map((d, i) => {
              return { label: d.name, value: d.id }
            })
          })
          channelData[0].channelIds.map((d, i) => {
            // 找到默认通道对应的samples
            if (Number(d.id) === Number(channel_id)) {
              component.setState({
                channelValue: d.id,
                checkName: d.name,
                samples: d.samples,
                activity: d.activity
              }, () => {
                component.getDynamicData(component.props)
              })
            }
          })
        }
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  getIndictor () {
    const { deviceData, historyCond } = this.props
    const sensorType = historyCond.monitors[0].sensorType
    const component = this
    const id = deviceData.id
    let api = `${__SERVICE_API__}`
    if (requestType === 'wx') {
      api = `${__WXSERVICE_API__}`
    }
    universalFetch(`${api}device/devices/${id}/monitors?group`)
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        const Indictor = json.result[sensorType][sensorType]
        this.setState({
          Indictor: Indictor
        }, () => {
          component.getChannel(component.props)
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  closeModal () {
    this.setState({
      visible: false
    })
    const { closeModal } = this.props
    closeModal()
  }
  getDynamicData (props: Props) {
    this.setState({
      loading: true,
      loading2: true
    })
    // opt_freq_h1_1 未注册
    const { Indictor, samples, channelValue, activity, checkName } = this.state
    let inds = ['dyna_value']
    // let indsName = ['动态数据']
    Indictor.map((d) => {
      inds.push(d.kmxVariableNameEn)
      // indsName.push(d.variableName)
    })
    // 一倍频相位幅值和二倍频相位幅值顺序有要求（便于左侧展示）
    let indsName = ['动态值', '一倍频相位', '一倍频幅值', '二倍频相位', '二倍频幅值', '0.5倍频幅值', '通频值', '转速', 'GAP电压', '有效值',
      '残余量' ]
    const { deviceData, historyCond } = props
    const fieldGroup = historyCond.monitors
    const deviceNo = deviceData.deviceNo.split('_')
    const postBody = JSON.stringify({
      fieldGroup: fieldGroup[0].En,
      fields: ['dyna_value', 'p1x', 'v1x', 'p2x', 'v2x', 'v3x', 'direc', 'speed', 'gap', 'rms',
        'rv' ],
      // fields: inds,
      sampleTime: props.checkTime,
      coValueFilter: {
        idFieldFilter: {
          factory_id: { '$eq': String(deviceNo[0]) },
          equipment_id: { '$eq': String(deviceNo[1]) },
          machine_id: { '$eq': String(deviceNo[2]) },
          datatype: { '$eq': '1' },
          // '$or': fieldGroup[0].channelIds.map((d, i) => {
          //   return { 'channel_id': { '$eq': String(d) } }
          // })
          '$or': [{ 'channel_id': { '$eq': String(channelValue) } }]
        }
      }
    })

    let api = `${__KMX_API__}`
    if (requestType === 'wx') {
      api = `${__WXKMX_API__}`
    }
    fetch(`${api}data-points`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: postBody
    })
    .then((res) => res.json())
    .then((json) => {
      if (json.code !== 0) {
        throw new Error(JSON.stringify({ code: json.code, message: json.message }))
      }
      const results = json.results
      if (results && results.length > 0) {
        if (!results[0].value) { // 如果value不存在 直接报错并空值
          this.noData()
          return
        }
        const len = results[0].value.split(',').length
        const speed = results.filter((dd) => dd.field === 'speed')
        this.setState({
          loading: false,
          samplesFinal: samples,
          activityFinal: activity,
          checkNameFinal: checkName,
          chartData: [{
            name: results[0].field,
            type: 'line',
            data: results[0].value.split(',').map((dd, ii) => {
              return Number(dd)
            })
          }],
          xData: results[0].value.split(',').map((d, i) => {
            return i / len
          }),
          requestData: '{ samples: ' + samples + ', value: [' + results[0].value.split(',').map((d, i) => {
            return d
          }) + '], speed: ' + speed[0].value + '}',
          infoData: results.map((d, i) => {
            return { key: d.field, name: indsName[i], value: d.value }
          })
        }, () => {
          this.getRequestData()
          const container = this.refs.chart
          const series = this.state.chartData
          const spectrumCharts = [
            {
              chart: container,
              title: '波形图',
              xtext: '序号',
              ytext: '幅值(μm)',
              series: series
            }
          ]
          this.draw(spectrumCharts)
        })
      } else {
        message.info('暂无数据')
        this.noData()
      }
    })
    .catch((error) => {
      console.error(error)
      message.error(error.message)
      this.noData()
    })
  }
  noData = () => {
    const { samples, activity, checkName } = this.state
    this.setState({
      loading: false,
      loading2: false,
      samplesFinal: samples,
      activityFinal: activity,
      checkNameFinal: checkName
    })
    // 无数据后波形频谱都是空的
    this.draw([
      {
        chart: this.refs.chart,
        title: '波形图',
        xtext: '序号',
        ytext: '幅值(μm)',
        series: []
      }
    ])
    this.draw([
      {
        chart: this.refs.chart2,
        title: '频谱图',
        xtext: '频率(Hz)',
        ytext: '幅值(μm)',
        series: []
      }
    ])
  }
  getRequestData () {
    this.setState({
      loading2: true
    })
    const { requestData } = this.state
    let api = `${__SPE_API__}`
    if (requestType === 'wx') {
      api = `${__WXSPE_API__}`
    }
    fetch(`${api}api/time`, {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(requestData)
    })
    .then(res => res.json())
    .then((json) => {
      const amp = json.amp
      const fre = json.fre
      if (fre && fre.length > 0) {
        const data2 = fre.map((d, i) => {
          return [Number(d), Number(amp[i])]
        })
        this.setState({
          loading2: false,
          chartData2: [
            {
              name: '幅值',
              type: 'line',
              data: data2
            },
            {
              type: 'scatter',
              // color: '#f00',
              marker: {
                 // symbol: 'circle',
                radius: 3
              },
              data: json.peak.map((d, i) => {
                const x = Number(d)
                return data2[x]
              })
            }
          ]
        }, () => {
          const container = this.refs.chart2
          const series = this.state.chartData2
          const spectrumCharts = [
            {
              chart: container,
              title: '频谱图',
              xtext: '频率(Hz)',
              ytext: '幅值(μm)',
              series: series
            }
          ]
          this.draw(spectrumCharts)
        })
      } else {
        this.setState({
          loading2: false,
          chartData2:[]
        }, () => {
          const container = this.refs.chart2
          const series = this.state.chartData2
          const spectrumCharts = [
            {
              chart: container,
              title: '频谱图',
              xtext: '频率(Hz)',
              ytext: '幅值(μm)',
              series: series
            }
          ]
          this.draw(spectrumCharts)
        })
      }
    })
    .catch((error) => {
      console.error(error)
      this.setState({
        loading2: false,
        chartData2:[]
      }, () => {
        const container = this.refs.chart2
        const series = this.state.chartData2
        const spectrumCharts = [
          {
            chart: container,
            title: '频谱图',
            xtext: '频率(Hz)',
            ytext: '幅值(μm)',
            series: series
          }
        ]
        this.draw(spectrumCharts)
      })
    })
  }
  draw (spectrumCharts: Array<Object>) {
    Highcharts.setOptions({ global: { useUTC: false } })
    spectrumCharts.map((d, i) => {
      const chart = d.chart
      Highcharts.chart(chart, {
        chart: {
          backgroundColor: 'transparent',
          zoomType: 'x'
        },
        title: {
          text: d.title,
          style: {
            fontSize: 12
          }
        },
        credits:{
          enabled: false
        },
        legend: {
          enabled: false
        },
        tooltip: {
          // shared: true,
          // crosshairs: true,
          formatter: function () {
            var x = this.x.toFixed(3) * 1000 / 1000
            var value = this.y.toFixed(3) * 1000 / 1000
            document.getElementById('guangbiao').innerHTML = value
            return x + '<br>幅值：' + value
          }
        },
        xAxis: {
          title: {
            text: d.xtext,
            align: 'high'
          }
          // categories: this.state.xData
        },
        yAxis: {
          lineWidth: 1,
          tickWidth: 1,
          title: {
            align: 'high',
            offset: 0,
            text: d.ytext,
            rotation: 0,
            y: -15
          }
        },
        plotOptions: {
          line: {
            lineWidth: 1,
            dataGrouping: {
              enabled: false
            }
          },
          series: {
            animation: true,
            allowPointSelect: true,
            cursor: 'pointer',
            point: {
              events: {
                select: function () {
                  const text = d.xtext + ':' + this.category.toFixed(3) * 1000 / 1000 + ', ' +
                  d.ytext + ':' + this.y.toFixed(3) * 1000 / 1000
                  const chart = this.series.chart
                  chart.xAxis[0].removePlotLine('plot-line-1')
                  chart.xAxis[0].addPlotLine({
                    value: this.category,
                    color: '#000',
                    width: 0.5,
                    id: 'plot-line-1'
                  })
                  if (!chart.lbl) {
                    chart.lbl = chart.renderer.label(text, 70, 10)
                      .attr({
                        padding: 5,
                        r: 5,
                        fill: '#f7f7f7',
                        zIndex: 5
                      })
                    .css({
                      color: '#000'
                    })
                      .add()
                  } else {
                    chart.lbl.attr({
                      text: text
                    })
                  }
                }
              }
            }
          }
        },
        series: d.series
      })
    })
  }
  channelChange = (values: Object) => {
    const channelIds = values.target.value
    const { channelData } = this.state
    let samples // 查找采样点
    // let rotatDirec // 旋转角度
    // let orientDegree // 安装角度
    let activity // 速度计算方式
    if (channelData.length > 0) {
      const sample = channelData[0].channelIds.filter((dd) => Number(dd.id) === Number(channelIds))
      samples = sample[0].samples
      // rotatDirec = sample[0].rotatDirec
      // orientDegree = sample[0].orientDegree
      activity = sample[0].activity
    }
    // const name = checkName.split('__')[0]
    this.setState({
      checkName: values.target.title,
      samples: samples,
      // rotatDirec: rotatDirec,
      // orientDegree: orientDegree,
      activity: activity,
      channelValue: values.target.value
    })
  }
  refer = () => {
    this.getDynamicData(this.props)
  }
  render () {
    const { loading, loading2, infoData, samplesFinal, plainOptions, channelValue, checkNameFinal } = this.state
    const { checkTime } = this.props
    const radioStyle = {
      display: 'block',
      paddingLeft: '10px'
    }
    // 速度计算方式
    const { activityFinal } = this.state
    let activityName = ''
    if (activityFinal === '0') {
      activityName = '有效'
    } else if (activityFinal === '1') {
      activityName = '无效'
    } else if (activityFinal === '2') {
      activityName = '无键'
    } else if (activityFinal === '3') {
      activityName = '模拟'
    } else if (activityFinal === '4') {
      activityName = '无键计算转速'
    }
    return (
      <div className={styles['main']}>
        <Row className={styles['mainCon']}>
          <Col span={6}>
            基本信息：
            <div className={styles['leftCon']}>
              <label key='a'> <span>当前时间:</span> <b>{moment(checkTime).format('YYYY-MM-DD HH:mm:ss')}</b></label>
              <label key='b'> <span>通道:</span> <b>{checkNameFinal}</b></label>
              <label key='bb'> <span>周期数:</span> <b>{samplesFinal}</b></label>
              {/* <label key='bb'> <span>采样点数:</span> <b>{samplesFinal}</b></label> */}
              {/* <label key='bc'> <span>转速计算:</span> <b>{activityName}</b></label> */}
              {
                infoData.map((d, i) => {
                  if (i === 7) {
                    let labelrpm = <div><label key='bc'> <span>转速计算:</span> <b>{activityName}</b></label>
                      <label key={i}> <span>转速(rpm):</span> <b>{d.value.toFixed(3) * 1000 / 1000}</b></label>
                    </div>
                    return labelrpm
                  }
                  if (i === 8) {
                    return <label key={i}> <span>GAP电压(V):</span> <b>{d.value.toFixed(3) * 1000 / 1000}</b></label>
                  }
                })
              }
              <label key='c'> <span>光标值:</span> <b id='guangbiao' /></label>
              {
                infoData.map((d, i) => {
                  if (i === 6) {
                    return <label key={i}> <span>通频值:</span> <b>{d.value.toFixed(3) * 1000 / 1000}</b></label>
                  }
                  if (i === 9) {
                    return <label key={i}> <span>有效值:</span> <b>{d.value.toFixed(3) * 1000 / 1000}</b></label>
                  }
                })
              }
              {
                infoData.map((d, i) => {
                  if (i === 1) {
                    return <label key={0}> <span>一倍频:</span> <b>{infoData[2].value.toFixed(3) * 1000 / 1000}
                      ∠ {infoData[1].value.toFixed(3) * 1000 / 1000}</b></label>
                  }
                  if (i === 3) {
                    return <label key={1}> <span>二倍频:</span> <b>{infoData[4].value.toFixed(3) * 1000 / 1000}
                    ∠ {infoData[3].value.toFixed(3) * 1000 / 1000}</b></label>
                  }
                  if (i === 10) {
                    return <label key={i}> <span>残余量:</span> <b>{d.value.toFixed(3) * 1000 / 1000}</b></label>
                  }
                })
              }
              <label key='d'> <span>单位:</span> <b>微米</b></label>
              {/* {
                infoData.map((d, i) => {
                  // 第0相动态值不显示，第1-4幅值相位特殊显示
                  if (i === 1) {
                    return <label key={0}> <span>一倍频:</span> <b>{infoData[2].value.toFixed(3) * 1000 / 1000}
                      ∠ {infoData[1].value.toFixed(3) * 1000 / 1000}</b></label>
                  }
                  if (i === 3) {
                    return <label key={1}> <span>二倍频:</span> <b>{infoData[4].value.toFixed(3) * 1000 / 1000}
                    ∠ {infoData[3].value.toFixed(3) * 1000 / 1000}</b></label>
                  }
                  if (i > 4) {
                    return <label key={i}> <span>{d.name}:</span> <b>{d.value.toFixed(3) * 1000 / 1000}</b></label>
                  }
                })
              } */}
            </div>
          </Col>
          <Col span={18}>
            <Popover content={
              <div>
                <div className={styles['conditionTop']}>
                  <RadioGroup onChange={this.channelChange} value={Number(channelValue)}>
                    {
                      plainOptions.map((d, i) => {
                        return <Radio style={radioStyle} key={i} title={d.label} value={d.value}>{d.label}</Radio>
                      })
                    }
                  </RadioGroup>
                </div>
                <p className={styles['leftFooter']}>
                  <Button type='primary' onClick={this.refer} disabled={loading}>绘制</Button>
                </p>
              </div>
            } trigger='click' title='通道：'>
              <Button type='primary' className={styles['conditionBtn']}>选择测点</Button>
            </Popover>
            <Spin spinning={loading} tip='加载中...'>
              <div ref='chart' className={styles['chart']} />
            </Spin>
            <Spin spinning={loading2} tip='加载中...'>
              <div ref='chart2' className={styles['chart']} />
            </Spin>
          </Col>
        </Row>
      </div>
    )
  }
}

export default Spectrum
